<template>
  <view class="page-container">
    <!-- 门店信息头部 -->
    <view class="store-header" v-if="storeInfo">
      <view class="store-info">
        <text class="store-name">{{ storeInfo.name }}</text>
        <text class="store-address">{{ storeInfo.address }}</text>
      </view>
      <view class="store-status">
        <uni-tag 
          :text="isCurrentlyOpen ? '营业中' : '休息中'" 
          :type="isCurrentlyOpen ? 'success' : 'error'" 
          size="small"
        />
      </view>
    </view>

    <scroll-view scroll-y class="content-scroll">
      <!-- 快速设置 -->
      <uni-card title="快速设置" :is-shadow="true">
        <view class="quick-settings">
          <view class="quick-item" @click="applyTemplate('24h')">
            <uni-icons type="clock" size="20" color="#007AFF"></uni-icons>
            <text class="quick-text">24小时营业</text>
          </view>
          <view class="quick-item" @click="applyTemplate('normal')">
            <uni-icons type="calendar" size="20" color="#007AFF"></uni-icons>
            <text class="quick-text">正常工作时间</text>
          </view>
          <view class="quick-item" @click="applyTemplate('weekend')">
            <uni-icons type="home" size="20" color="#007AFF"></uni-icons>
            <text class="quick-text">仅周末营业</text>
          </view>
        </view>
      </uni-card>

      <!-- 营业时间设置 -->
      <uni-card title="营业时间设置" :is-shadow="true">
        <view class="mode-selector">
          <uni-segmented-control 
            :current="currentMode" 
            :values="['简单模式', '详细模式']" 
            @clickItem="switchMode"
            style-type="button"
          />
        </view>

        <!-- 简单模式 -->
        <view v-if="currentMode === 0" class="simple-mode">
          <view class="time-group">
            <view class="group-header">
              <text class="group-title">工作日 (周一至周五)</text>
              <uni-switch 
                :checked="simpleData.workday.isOpen" 
                @change="handleWorkdayToggle"
              />
            </view>
            <view v-if="simpleData.workday.isOpen" class="time-settings">
              <view class="time-picker-row">
                <text class="time-label">营业时间</text>
                <view class="time-picker-group">
                  <uni-datetime-picker 
                    v-model="simpleData.workday.openTime"
                    type="time"
                    @change="updateBusinessHours"
                  >
                    <template v-slot:default>
                      <uni-easyinput 
                        :value="simpleData.workday.openTime" 
                        placeholder="开始时间"
                        readonly
                      />
                    </template>
                  </uni-datetime-picker>
                  <text class="time-separator">至</text>
                  <uni-datetime-picker 
                    v-model="simpleData.workday.closeTime"
                    type="time"
                    @change="updateBusinessHours"
                  >
                    <template v-slot:default>
                      <uni-easyinput 
                        :value="simpleData.workday.closeTime" 
                        placeholder="结束时间"
                        readonly
                      />
                    </template>
                  </uni-datetime-picker>
                </view>
              </view>
              
              <!-- 午休时间 -->
              <view class="break-time-section">
                <view class="break-header">
                  <text class="break-title">午休时间</text>
                  <uni-switch 
                    :checked="simpleData.workday.hasBreak" 
                    @change="handleWorkdayBreakToggle"
                  />
                </view>
                <view v-if="simpleData.workday.hasBreak" class="time-picker-row">
                  <view class="time-picker-group">
                    <uni-datetime-picker 
                      v-model="simpleData.workday.breakStart"
                      type="time"
                      @change="updateBusinessHours"
                    >
                      <template v-slot:default>
                        <uni-easyinput 
                          :value="simpleData.workday.breakStart" 
                          placeholder="午休开始"
                          readonly
                        />
                      </template>
                    </uni-datetime-picker>
                    <text class="time-separator">至</text>
                    <uni-datetime-picker 
                      v-model="simpleData.workday.breakEnd"
                      type="time"
                      @change="updateBusinessHours"
                    >
                      <template v-slot:default>
                        <uni-easyinput 
                          :value="simpleData.workday.breakEnd" 
                          placeholder="午休结束"
                          readonly
                        />
                      </template>
                    </uni-datetime-picker>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <view class="time-group">
            <view class="group-header">
              <text class="group-title">周末 (周六至周日)</text>
              <uni-switch 
                :checked="simpleData.weekend.isOpen" 
                @change="handleWeekendToggle"
              />
            </view>
            <view v-if="simpleData.weekend.isOpen" class="time-settings">
              <view class="time-picker-row">
                <text class="time-label">营业时间</text>
                <view class="time-picker-group">
                  <uni-datetime-picker 
                    v-model="simpleData.weekend.openTime"
                    type="time"
                    @change="updateBusinessHours"
                  >
                    <template v-slot:default>
                      <uni-easyinput 
                        :value="simpleData.weekend.openTime" 
                        placeholder="开始时间"
                        readonly
                      />
                    </template>
                  </uni-datetime-picker>
                  <text class="time-separator">至</text>
                  <uni-datetime-picker 
                    v-model="simpleData.weekend.closeTime"
                    type="time"
                    @change="updateBusinessHours"
                  >
                    <template v-slot:default>
                      <uni-easyinput 
                        :value="simpleData.weekend.closeTime" 
                        placeholder="结束时间"
                        readonly
                      />
                    </template>
                  </uni-datetime-picker>
                </view>
              </view>
              
              <!-- 午休时间 -->
              <view class="break-time-section">
                <view class="break-header">
                  <text class="break-title">午休时间</text>
                  <uni-switch 
                    :checked="simpleData.weekend.hasBreak" 
                    @change="handleWeekendBreakToggle"
                  />
                </view>
                <view v-if="simpleData.weekend.hasBreak" class="time-picker-row">
                  <view class="time-picker-group">
                    <uni-datetime-picker 
                      v-model="simpleData.weekend.breakStart"
                      type="time"
                      @change="updateBusinessHours"
                    >
                      <template v-slot:default>
                        <uni-easyinput 
                          :value="simpleData.weekend.breakStart" 
                          placeholder="午休开始"
                          readonly
                        />
                      </template>
                    </uni-datetime-picker>
                    <text class="time-separator">至</text>
                    <uni-datetime-picker 
                      v-model="simpleData.weekend.breakEnd"
                      type="time"
                      @change="updateBusinessHours"
                    >
                      <template v-slot:default>
                        <uni-easyinput 
                          :value="simpleData.weekend.breakEnd" 
                          placeholder="午休结束"
                          readonly
                        />
                      </template>
                    </uni-datetime-picker>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 详细模式 -->
        <view v-else class="advanced-mode">
          <view 
            v-for="(day, index) in advancedData.daily" 
            :key="index" 
            class="day-group"
          >
            <view class="group-header">
              <text class="group-title">{{ day.dayName }}</text>
              <uni-switch 
                :checked="day.isOpen" 
                @change="(e) => handleDayToggle(index, e)"
              />
            </view>
            <view v-if="day.isOpen" class="time-settings">
              <view class="time-picker-row">
                <text class="time-label">营业时间</text>
                <view class="time-picker-group">
                  <uni-datetime-picker 
                    v-model="day.openTime"
                    type="time"
                    @change="updateBusinessHours"
                  >
                    <template v-slot:default>
                      <uni-easyinput 
                        :value="day.openTime" 
                        placeholder="开始时间"
                        readonly
                      />
                    </template>
                  </uni-datetime-picker>
                  <text class="time-separator">至</text>
                  <uni-datetime-picker 
                    v-model="day.closeTime"
                    type="time"
                    @change="updateBusinessHours"
                  >
                    <template v-slot:default>
                      <uni-easyinput 
                        :value="day.closeTime" 
                        placeholder="结束时间"
                        readonly
                      />
                    </template>
                  </uni-datetime-picker>
                </view>
              </view>
              
              <!-- 午休时间 -->
              <view class="break-time-section">
                <view class="break-header">
                  <text class="break-title">午休时间</text>
                  <uni-switch 
                    :checked="day.hasBreak" 
                    @change="(e) => handleDayBreakToggle(index, e)"
                  />
                </view>
                <view v-if="day.hasBreak" class="time-picker-row">
                  <view class="time-picker-group">
                    <uni-datetime-picker 
                      v-model="day.breakStart"
                      type="time"
                      @change="updateBusinessHours"
                    >
                      <template v-slot:default>
                        <uni-easyinput 
                          :value="day.breakStart" 
                          placeholder="午休开始"
                          readonly
                        />
                      </template>
                    </uni-datetime-picker>
                    <text class="time-separator">至</text>
                    <uni-datetime-picker 
                      v-model="day.breakEnd"
                      type="time"
                      @change="updateBusinessHours"
                    >
                      <template v-slot:default>
                        <uni-easyinput 
                          :value="day.breakEnd" 
                          placeholder="午休结束"
                          readonly
                        />
                      </template>
                    </uni-datetime-picker>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </uni-card>

      <!-- 特殊日期设置 -->
      <uni-card title="特殊日期设置" :is-shadow="true">
        <view class="special-dates">
          <view class="special-header">
            <text class="special-title">节假日和特殊营业时间</text>
            <button class="add-special-btn" @click="showAddSpecialDate">
              <uni-icons type="plus" size="16" color="#007AFF"></uni-icons>
              <text class="add-text">添加</text>
            </button>
          </view>
          
          <view v-if="specialDates.length > 0" class="special-list">
            <view 
              v-for="(special, index) in specialDates" 
              :key="index"
              class="special-item"
            >
              <view class="special-info">
                <text class="special-date">{{ formatSpecialDate(special.date) }}</text>
                <text class="special-desc">{{ special.description }}</text>
                <text class="special-time" v-if="special.isOpen">
                  {{ special.openTime }} - {{ special.closeTime }}
                </text>
                <text class="special-closed" v-else>休息</text>
              </view>
              <view class="special-actions">
                <button class="edit-special-btn" @click="editSpecialDate(index)">
                  <uni-icons type="compose" size="16" color="#007AFF"></uni-icons>
                </button>
                <button class="delete-special-btn" @click="deleteSpecialDate(index)">
                  <uni-icons type="trash" size="16" color="#FF3B30"></uni-icons>
                </button>
              </view>
            </view>
          </view>
          
          <view v-else class="empty-special">
            <text class="empty-text">暂无特殊日期设置</text>
          </view>
        </view>
      </uni-card>

      <!-- 营业状态预览 -->
      <uni-card title="本周营业状态" :is-shadow="true">
        <view class="week-preview">
          <view 
            v-for="(day, index) in weekPreview" 
            :key="index"
            class="preview-day"
            :class="{ today: day.isToday }"
          >
            <text class="preview-date">{{ day.date }}</text>
            <text class="preview-week">{{ day.weekDay }}</text>
            <view class="preview-status">
              <text v-if="day.isOpen" class="preview-time">{{ day.timeRange }}</text>
              <text v-else class="preview-closed">休息</text>
            </view>
          </view>
        </view>
      </uni-card>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions safe-area-inset-bottom">
      <button class="reset-btn" @click="resetToDefault">重置</button>
      <button class="save-btn" @click="saveBusinessHours">保存设置</button>
    </view>

    <!-- 特殊日期弹窗 -->
    <uni-popup ref="specialDatePopup" type="center">
      <view class="special-modal">
        <view class="modal-header">
          <text class="modal-title">{{ editingSpecialIndex >= 0 ? '编辑' : '添加' }}特殊日期</text>
          <uni-icons type="close" size="20" @click="closeSpecialModal"></uni-icons>
        </view>
        <view class="modal-content">
          <uni-forms ref="specialFormRef" :modelValue="currentSpecial" :rules="specialRules">
            <uni-forms-item label="日期" name="date" required>
              <uni-datetime-picker 
                v-model="currentSpecial.date"
                type="date"
              >
                <template v-slot:default>
                  <uni-easyinput 
                    :value="currentSpecial.date" 
                    placeholder="选择日期"
                    readonly
                  />
                </template>
              </uni-datetime-picker>
            </uni-forms-item>
            <uni-forms-item label="说明" name="description" required>
              <uni-easyinput 
                v-model="currentSpecial.description" 
                placeholder="如：春节、国庆节等"
              />
            </uni-forms-item>
            <uni-forms-item label="是否营业" name="isOpen">
              <uni-switch 
                :checked="currentSpecial.isOpen" 
                @change="handleSpecialOpenToggle"
              />
            </uni-forms-item>
            <uni-forms-item v-if="currentSpecial.isOpen" label="营业时间" name="openTime" required>
              <view class="time-picker-group">
                <uni-datetime-picker 
                  v-model="currentSpecial.openTime"
                  type="time"
                >
                  <template v-slot:default>
                    <uni-easyinput 
                      :value="currentSpecial.openTime" 
                      placeholder="开始时间"
                      readonly
                    />
                  </template>
                </uni-datetime-picker>
                <text class="time-separator">至</text>
                <uni-datetime-picker 
                  v-model="currentSpecial.closeTime"
                  type="time"
                >
                  <template v-slot:default>
                    <uni-easyinput 
                      :value="currentSpecial.closeTime" 
                      placeholder="结束时间"
                      readonly
                    />
                  </template>
                </uni-datetime-picker>
              </view>
            </uni-forms-item>
          </uni-forms>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeSpecialModal">取消</button>
          <button class="confirm-btn" @click="saveSpecialDate">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { fetchStoreDetail, updateStore } from '@/api/store';
import type { Store } from '@/types/store';

const storeInfo = ref<Store | null>(null);
const currentMode = ref(0); // 0: 简单模式, 1: 详细模式
const specialDatePopup = ref<any>(null);
const specialFormRef = ref<any>(null);
const editingSpecialIndex = ref(-1);

const storeId = ref<number | null>(null);

const simpleData = reactive({
  workday: {
    isOpen: true,
    openTime: '09:00',
    closeTime: '18:00',
    hasBreak: false,
    breakStart: '12:00',
    breakEnd: '13:00',
  },
  weekend: {
    isOpen: true,
    openTime: '10:00',
    closeTime: '17:00',
    hasBreak: false,
    breakStart: '12:00',
    breakEnd: '13:00',
  },
});

const advancedData = reactive({
  daily: [
    { dayName: '周一', isOpen: true, openTime: '09:00', closeTime: '18:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' },
    { dayName: '周二', isOpen: true, openTime: '09:00', closeTime: '18:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' },
    { dayName: '周三', isOpen: true, openTime: '09:00', closeTime: '18:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' },
    { dayName: '周四', isOpen: true, openTime: '09:00', closeTime: '18:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' },
    { dayName: '周五', isOpen: true, openTime: '09:00', closeTime: '18:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' },
    { dayName: '周六', isOpen: true, openTime: '10:00', closeTime: '17:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' },
    { dayName: '周日', isOpen: true, openTime: '10:00', closeTime: '17:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' },
  ],
});

const specialDates = ref<any[]>([]);

const currentSpecial = reactive({
  date: '',
  description: '',
  isOpen: true,
  openTime: '09:00',
  closeTime: '18:00',
});

const specialRules = {
  date: { rules: [{ required: true, errorMessage: '请选择日期' }] },
  description: { rules: [{ required: true, errorMessage: '请输入说明' }] },
  openTime: { rules: [{ required: true, errorMessage: '请选择开始时间' }] },
};

// 计算当前是否营业
const isCurrentlyOpen = computed(() => {
  const now = new Date();
  const currentDay = now.getDay(); // 0: 周日, 1: 周一, ..., 6: 周六
  const currentTime = now.getHours() * 60 + now.getMinutes();
  
  let dayConfig;
  if (currentMode.value === 0) {
    // 简单模式
    if (currentDay >= 1 && currentDay <= 5) {
      dayConfig = simpleData.workday;
    } else {
      dayConfig = simpleData.weekend;
    }
  } else {
    // 详细模式
    const dayIndex = currentDay === 0 ? 6 : currentDay - 1; // 转换为数组索引
    dayConfig = advancedData.daily[dayIndex];
  }
  
  if (!dayConfig.isOpen) return false;
  
  const openTime = parseTime(dayConfig.openTime);
  const closeTime = parseTime(dayConfig.closeTime);
  
  return currentTime >= openTime && currentTime <= closeTime;
});

// 计算本周营业状态预览
const weekPreview = computed(() => {
  const today = new Date();
  const preview = [];
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(today);
    date.setDate(today.getDate() + i);
    
    const dayOfWeek = date.getDay();
    const dayIndex = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
    
    let dayConfig;
    if (currentMode.value === 0) {
      if (dayOfWeek >= 1 && dayOfWeek <= 5) {
        dayConfig = simpleData.workday;
      } else {
        dayConfig = simpleData.weekend;
      }
    } else {
      dayConfig = advancedData.daily[dayIndex];
    }
    
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    
    preview.push({
      date: `${date.getMonth() + 1}/${date.getDate()}`,
      weekDay: `周${weekDays[dayOfWeek]}`,
      isToday: i === 0,
      isOpen: dayConfig.isOpen,
      timeRange: dayConfig.isOpen ? `${dayConfig.openTime}-${dayConfig.closeTime}` : '',
    });
  }
  
  return preview;
});

const parseTime = (timeStr: string) => {
  const [hours, minutes] = timeStr.split(':').map(Number);
  return hours * 60 + minutes;
};

const switchMode = (e: any) => {
  currentMode.value = e.currentIndex;
  updateBusinessHours();
};

const handleWorkdayToggle = (e: any) => {
  simpleData.workday.isOpen = e.detail.value;
  updateBusinessHours();
};

const handleWeekendToggle = (e: any) => {
  simpleData.weekend.isOpen = e.detail.value;
  updateBusinessHours();
};

const handleWorkdayBreakToggle = (e: any) => {
  simpleData.workday.hasBreak = e.detail.value;
  updateBusinessHours();
};

const handleWeekendBreakToggle = (e: any) => {
  simpleData.weekend.hasBreak = e.detail.value;
  updateBusinessHours();
};

const handleDayToggle = (index: number, e: any) => {
  advancedData.daily[index].isOpen = e.detail.value;
  updateBusinessHours();
};

const handleDayBreakToggle = (index: number, e: any) => {
  advancedData.daily[index].hasBreak = e.detail.value;
  updateBusinessHours();
};

const updateBusinessHours = () => {
  // 这里可以实时保存到本地存储或发送到服务器
  console.log('营业时间已更新');
};

// 应用模板
const applyTemplate = (template: string) => {
  switch (template) {
    case '24h':
      // 24小时营业
      if (currentMode.value === 0) {
        simpleData.workday = { isOpen: true, openTime: '00:00', closeTime: '23:59', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' };
        simpleData.weekend = { isOpen: true, openTime: '00:00', closeTime: '23:59', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' };
      } else {
        advancedData.daily.forEach(day => {
          day.isOpen = true;
          day.openTime = '00:00';
          day.closeTime = '23:59';
          day.hasBreak = false;
        });
      }
      break;
    case 'normal':
      // 正常工作时间
      if (currentMode.value === 0) {
        simpleData.workday = { isOpen: true, openTime: '09:00', closeTime: '18:00', hasBreak: true, breakStart: '12:00', breakEnd: '13:00' };
        simpleData.weekend = { isOpen: true, openTime: '10:00', closeTime: '17:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' };
      } else {
        advancedData.daily.forEach((day, index) => {
          day.isOpen = true;
          if (index < 5) { // 工作日
            day.openTime = '09:00';
            day.closeTime = '18:00';
            day.hasBreak = true;
          } else { // 周末
            day.openTime = '10:00';
            day.closeTime = '17:00';
            day.hasBreak = false;
          }
        });
      }
      break;
    case 'weekend':
      // 仅周末营业
      if (currentMode.value === 0) {
        simpleData.workday.isOpen = false;
        simpleData.weekend = { isOpen: true, openTime: '10:00', closeTime: '18:00', hasBreak: false, breakStart: '12:00', breakEnd: '13:00' };
      } else {
        advancedData.daily.forEach((day, index) => {
          if (index < 5) { // 工作日
            day.isOpen = false;
          } else { // 周末
            day.isOpen = true;
            day.openTime = '10:00';
            day.closeTime = '18:00';
            day.hasBreak = false;
          }
        });
      }
      break;
  }
  updateBusinessHours();
  uni.showToast({ title: '模板已应用' });
};

// 特殊日期相关方法
const showAddSpecialDate = () => {
  editingSpecialIndex.value = -1;
  resetCurrentSpecial();
  specialDatePopup.value?.open();
};

const editSpecialDate = (index: number) => {
  editingSpecialIndex.value = index;
  const special = specialDates.value[index];
  Object.assign(currentSpecial, special);
  specialDatePopup.value?.open();
};

const deleteSpecialDate = (index: number) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个特殊日期设置吗？',
    success: (res) => {
      if (res.confirm) {
        specialDates.value.splice(index, 1);
        uni.showToast({ title: '删除成功' });
      }
    }
  });
};

const resetCurrentSpecial = () => {
  currentSpecial.date = '';
  currentSpecial.description = '';
  currentSpecial.isOpen = true;
  currentSpecial.openTime = '09:00';
  currentSpecial.closeTime = '18:00';
};

const handleSpecialOpenToggle = (e: any) => {
  currentSpecial.isOpen = e.detail.value;
};

const saveSpecialDate = () => {
  specialFormRef.value.validate().then(() => {
    const newSpecial = { ...currentSpecial };
    
    if (editingSpecialIndex.value >= 0) {
      // 编辑
      specialDates.value[editingSpecialIndex.value] = newSpecial;
      uni.showToast({ title: '修改成功' });
    } else {
      // 添加
      specialDates.value.push(newSpecial);
      uni.showToast({ title: '添加成功' });
    }
    
    // 按日期排序
    specialDates.value.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
    
    closeSpecialModal();
  }).catch((err: any) => {
    console.log('表单校验失败', err);
  });
};

const closeSpecialModal = () => {
  specialDatePopup.value?.close();
  resetCurrentSpecial();
};

const formatSpecialDate = (dateStr: string) => {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
  const weekDay = weekDays[date.getDay()];
  return `${year}-${month}-${day} 周${weekDay}`;
};

// 重置为默认设置
const resetToDefault = () => {
  uni.showModal({
    title: '确认重置',
    content: '确定要重置为默认营业时间吗？',
    success: (res) => {
      if (res.confirm) {
        // 重置简单模式数据
        simpleData.workday = {
          isOpen: true,
          openTime: '09:00',
          closeTime: '18:00',
          hasBreak: false,
          breakStart: '12:00',
          breakEnd: '13:00',
        };
        simpleData.weekend = {
          isOpen: true,
          openTime: '10:00',
          closeTime: '17:00',
          hasBreak: false,
          breakStart: '12:00',
          breakEnd: '13:00',
        };
        
        // 重置详细模式数据
        advancedData.daily.forEach((day, index) => {
          day.isOpen = true;
          if (index < 5) { // 工作日
            day.openTime = '09:00';
            day.closeTime = '18:00';
          } else { // 周末
            day.openTime = '10:00';
            day.closeTime = '17:00';
          }
          day.hasBreak = false;
          day.breakStart = '12:00';
          day.breakEnd = '13:00';
        });
        
        // 清空特殊日期
        specialDates.value = [];
        
        uni.showToast({ title: '已重置为默认设置' });
      }
    }
  });
};

// 保存营业时间设置
const saveBusinessHours = async () => {
  if (!storeId.value) return;
  
  try {
    uni.showLoading({ title: '保存中...' });
    
    const businessHoursData = {
      mode: currentMode.value,
      simple: simpleData,
      advanced: advancedData,
      special: specialDates.value,
    };
    
    await updateStore(storeId.value, {
      business_hours: JSON.stringify(businessHoursData),
    });
    
    uni.showToast({ title: '保存成功' });
  } catch (error) {
    console.error('保存营业时间失败:', error);
    uni.showToast({ title: '保存失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 获取门店信息
const getStoreInfo = async () => {
  if (!storeId.value) return;
  
  try {
    const res = await fetchStoreDetail(storeId.value);
    storeInfo.value = res;
    
    // 解析营业时间数据
    if (res.business_hours) {
      try {
        const businessHoursData = JSON.parse(res.business_hours);
        if (businessHoursData.mode !== undefined) {
          currentMode.value = businessHoursData.mode;
        }
        if (businessHoursData.simple) {
          Object.assign(simpleData, businessHoursData.simple);
        }
        if (businessHoursData.advanced) {
          Object.assign(advancedData, businessHoursData.advanced);
        }
        if (businessHoursData.special) {
          specialDates.value = businessHoursData.special;
        }
      } catch (error) {
        console.error('解析营业时间数据失败:', error);
      }
    }
  } catch (error) {
    console.error('获取门店信息失败:', error);
    uni.showToast({ title: '获取门店信息失败', icon: 'none' });
  }
};

onLoad((options: any) => {
  if (options.storeId) {
    storeId.value = Number(options.storeId);
    uni.setNavigationBarTitle({ title: '营业时间设置' });
    getStoreInfo();
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.store-header {
  background-color: #fff;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.store-info {
  flex: 1;
}

.store-name {
  font-size: 18px;
  font-weight: bold;
  color: var(--text-color);
  display: block;
  margin-bottom: 4px;
}

.store-address {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.content-scroll {
  flex: 1;
  height: 0;
  padding-bottom: 80px;
}

.uni-card {
  margin: 10px !important;
}

.quick-settings {
  display: flex;
  justify-content: space-around;
  gap: 10px;
}

.quick-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  flex: 1;
  min-width: 0;
}

.quick-text {
  font-size: 12px;
  color: var(--text-color);
  margin-top: 8px;
  text-align: center;
}

.mode-selector {
  margin-bottom: 20px;
}

.time-group, .day-group {
  margin-bottom: 16px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.group-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-color);
}

.time-settings {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.time-picker-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-label {
  font-size: 14px;
  color: var(--text-color-secondary);
  width: 60px;
  flex-shrink: 0;
}

.time-picker-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.time-separator {
  font-size: 14px;
  color: var(--text-color-secondary);
  margin: 0 4px;
}

.break-time-section {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e0e0e0;
}

.break-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.break-title {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.special-dates {
  .special-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .special-title {
    font-size: 16px;
    font-weight: 500;
    color: var(--text-color);
  }

  .add-special-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 6px 12px;
    background-color: #f0f8ff;
    border: 1px solid var(--primary-color);
    border-radius: 6px;
  }

  .add-text {
    font-size: 14px;
    color: var(--primary-color);
  }
}

.special-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.special-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.special-info {
  flex: 1;
}

.special-date {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color);
  display: block;
  margin-bottom: 4px;
}

.special-desc {
  font-size: 12px;
  color: var(--text-color-secondary);
  display: block;
  margin-bottom: 4px;
}

.special-time {
  font-size: 13px;
  color: var(--primary-color);
}

.special-closed {
  font-size: 13px;
  color: #ff4757;
}

.special-actions {
  display: flex;
  gap: 8px;
}

.edit-special-btn, .delete-special-btn {
  padding: 6px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.edit-special-btn {
  background-color: #f0f8ff;
}

.delete-special-btn {
  background-color: #fff0f0;
}

.empty-special {
  text-align: center;
  padding: 20px;
}

.empty-text {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.week-preview {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-day {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
  
  &.today {
    background-color: #e3f2fd;
    border: 1px solid var(--primary-color);
  }
}

.preview-date {
  font-size: 14px;
  color: var(--text-color);
  width: 50px;
}

.preview-week {
  font-size: 14px;
  color: var(--text-color-secondary);
  width: 40px;
}

.preview-status {
  flex: 1;
  text-align: right;
}

.preview-time {
  font-size: 14px;
  color: var(--primary-color);
}

.preview-closed {
  font-size: 14px;
  color: #ff4757;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  display: flex;
  gap: 10px;
}

.reset-btn, .save-btn {
  flex: 1;
  height: 44px;
  border-radius: var(--border-radius);
  font-size: 16px;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.save-btn {
  background-color: var(--primary-color);
  color: #fff;
}

.special-modal {
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 20px;
  width: 320px;
  max-width: 90vw;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.modal-content {
  margin-bottom: 20px;
}

.modal-footer {
  display: flex;
  gap: 10px;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 44px;
  border-radius: var(--border-radius);
  font-size: 16px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: var(--primary-color);
  color: #fff;
}
</style>
